package com.otitan.la.forest.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.MenuRoleDTO;
import com.otitan.la.forest.system.entity.MenuRoleEntity;
import com.otitan.la.forest.system.mapper.MenuRoleMapper;
import com.otitan.la.forest.system.service.MenuRoleService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

@Slf4j
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRoleEntity> implements MenuRoleService {

    /**
    * 当前方法实现说明
    * @author Sunke
    * @param menuRoleDTO, bindingResult
    * @return com.otitan.webapp.framework.basepro.model.DataResult
    * @exception
    * @date 2020/9/24 0024 15:35
    */
    @Transactional
    @Override
    public DataResult add(MenuRoleDTO menuRoleDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
            MenuRoleEntity menuRoleEntity = new MenuRoleEntity();
            menuRoleEntity.setRoleId(menuRoleDTO.getRoleId());
            menuRoleEntity.setMenuId(menuRoleDTO.getMenuId());
        // 删除已存在的关联关系，防止主键冲突异常
        boolean isRemove=removeMenuAndRoleId(menuRoleDTO);
        boolean isSuccess;
        if(menuRoleDTO.getIsOpen().equals("yes")){
            isSuccess = this.save(menuRoleEntity);
            return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
        }
        return isRemove ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    /**
    * 删除已存在的关联关系，防止主键冲突异常
    * @author Sunke
    * @param  menuRoleDTO
    * @return boolean
    * @exception
    * @date 2020/9/24 0024 15:37
    */
    private boolean removeMenuAndRoleId(MenuRoleDTO menuRoleDTO) {
        LambdaQueryWrapper<MenuRoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MenuRoleEntity::getRoleId, menuRoleDTO.getRoleId())
                .eq(MenuRoleEntity::getMenuId, menuRoleDTO.getMenuId());
        return this.remove(queryWrapper);
    }

}